#!/bin/bash
set -e;
sudo iptables-save |sudo tee /etc/network/iptables.up.rules;
default_ip_net=`sudo cat /etc/iptables/rules.v4|grep 'openvpn-nat-rule'|head -1|awk '{print$4}'|awk -F'/' '{print$1}'`

ip_net='10.118.144.0'
if [ "${default_ip_net}" != "" ];then
    sudo sed -i "s/${default_ip_net}/${ip_net}/g" /etc/iptables/rules.v4;
fi
sudo sed -i "s/^server.*/server ${ip_net} 255.255.255.0/g"  /etc/openvpn/server.conf;
sudo sed -i "s/pivpnNET=${default_ip_net}/pivpnNET=${ip_net}/g" /etc/pivpn/openvpn/setupVars.conf;



sudo sed -i 's/^push "dhcp-option DNS.*/##push "dhcp-option DNS XXXX/g'  /etc/openvpn/server.conf;

sudo sed -i 's/^#duplicate-cn/duplicate-cn/g'  /etc/openvpn/server.conf;


# echo 'management 127.0.0.1 55555'|sudo tee -a /etc/openvpn/server.conf;


net_interface=`ip a|grep  'state UP'|awk '{print$2}'|awk -F':' '{print$1}'|head -1`
sudo sed -i "s/IPv4dev=.*/IPv4dev=${net_interface}/g" /etc/pivpn/openvpn/setupVars.conf;

sudo iptables-save|grep FORWARD |grep 'openvpn-forward-rule'| while read line;do

sudo iptables -t FORWARD -D ${line:2:140} || echo 'skip'

done;


sudo iptables-save|grep POSTROUTING |grep 'openvpn-nat-rule'| while read line;do

sudo iptables -t nat -D ${line:2:140} || echo 'skip'

done;



sudo /opt/pivpn/self_check.sh openvpn  <<EOF
y
y
EOF

###/etc/iptables/rules.v4
###-A POSTROUTING -s 10.117.49.0/24 -o wlan0 -m comment --comment openvpn-nat-rule -j MASQUERADE
sudo rm -f /etc/openvpn/ccd/*||echo "ok";
sudo systemctl restart openvpn


